<template>
  <div :class="uploadClass">
    <div class="demo-upload-list" :key="index" v-for="(item,index) in uploadList">
      <template v-if="item.status === 'finished'">
        <template v-if="uploadType === 'image'">
          <img :src="item.url">
          <div class="demo-upload-list-cover">
            <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
            <Icon type="ios-trash-outline" @click.native="handleRemove(item,index)"></Icon>
          </div>
        </template>
        <template v-else>
          <div class="fc-files">
            <i class="ivu-icon ivu-icon-md-document" style="font-size: 40px;"></i>
            <div class="fc-upload-cover">
              <Icon type="ios-trash-outline" @click.native="handleRemove(item,index)"></Icon>
            </div>
          </div>
        </template>
      </template>
      <template v-else>
        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
      </template>
    </div>
    <Upload
      ref="upload"
      :headers="headers"
      :show-upload-list="false"
      :default-file-list="defaultList"
      :on-success="handleSuccess"
      :on-error="handleError"
      :accept="accept"
      :max-size="2048"
      name="img_url"
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
      :before-upload="handleBeforeUpload"
      type="drag"
      :action="action"
      style="display: inline-block;width:58px;"
    >
      <div class="upload-btn">
        <Icon :type="uploadType=='image'?'ios-camera': 'ios-cloud-upload-outline'" size="20"></Icon>
      </div>
    </Upload>
    <div
      class="upload-tip"
    >{{uploadType ==='image' ? '每张不大于1MB，支持jpg、gif、png、jpeg、bmp格式, 支持最低尺寸640px * 230px': '说明：一个产品对应多个条形码，可以手机上核销，也可以门店扫码核销'}}</div>

    <Modal title="View Image" v-model="visible">
      <img :src="selectPic.url" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>
<script>
import { getToken, deepCopy } from "@/libs/util";

export default {
  name: "UploadImage",
  props: {
    action: {
      type: String
    },
    value: {
      type: [String, Array]
    },
    uploadType: {
      type: String,
      default: "image"
    },
    maxLength: {
      type: [Number, String],
      default: 1
    },
    accept: {
      type: String,
      default: ".bmp, .jpg, .png, .gif"
    },
    beforeUpload: Function
  },
  data() {
    return {
      defaultList: [],
      visible: false,
      uploadList: [],
      headers: {
        Authorization: getToken(),
        Accept: "application/vnd.hualaishi.v1+json"
      },
      selectPic: {}
    };
  },
  computed: {
    uploadClass() {
      if (this.maxLength == 1 && this.uploadList.length == 1) {
        return "fc-upload fc-hide-btn";
      }
      return "fc-upload";
    }
  },
  methods: {
    handleError(error, file, fileList) {
      if (file.errors.img_url && Array.isArray(file.errors.img_url)) {
        this.$Message.error(file.errors.img_url[0]);
      } else {
        this.$Message.error(file.message);
      }
    },
    handleView(item) {
      this.selectPic = item;
      this.visible = true;
    },
    handleRemove(file, index) {
      // const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(index, 1);
      this.uploadList = this.$refs.upload.fileList;
      if (file.url) {
        this.$emit("input", this.value.filter(v => v != file.url));
      }
    },
    handleSuccess(res, file) {
      file.url = res.data.full_path;
      file.name = res.data.save_path.split("/").pop();
      let value = res.data.full_path;
      if (Array.isArray(this.value)) {
        value = deepCopy(this.value).concat([value]);
      }
      this.$emit("input", value);
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式不正确",
        desc: "文件格式 " + file.name + " 是错误的, 请选择 jpg 或者 png."
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "超出文件大小限制",
        desc: "文件  " + file.name + " 太大, 最大支持 2M."
      });
    },
    handleBeforeUpload(file) {
      if (!this.beforeUpload) {
        const check = this.uploadList.length < this.maxLength;
        if (!check) {
          this.$Notice.warning({
            title: `最多可上传${this.maxLength}张图片`
          });
        }
        return check;
      } else {
        this.uploadList = [
          {
            name: "avatar.ddd",
            url:
              "https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar",
            status: "finished"
          }
        ];
        this.beforeUpload(file);
        return false;
      }
    }
  },
  mounted() {
    if (this.value) {
      if (Array.isArray(this.value)) {
        this.defaultList = this.value.map(v => {
          return {
            name: v.split("/").pop(),
            url: v
          };
        });
      } else {
        this.defaultList = [
          {
            name: this.value.split("/").pop(),
            url: this.value
          }
        ];
      }
    }
    this.uploadList = this.$refs.upload.fileList;
  },
  watch: {
    value(val) {
      if (Array.isArray(val)) {
        this.uploadList = val.map(v => {
          return {
            name: v.split("/").pop(),
            url: v,
            status: "finished"
          };
        });
      } else {
        if (this.uploadType == "image" && this.value) {
          this.uploadList = [
            {
              name: this.value.split("/").pop(),
              url: this.value,
              status: "finished"
            }
          ];
        } else if (this.uploadType == "file") {
          this.uploadList = [
            {
              name: this.value.name,
              url: this.value.name,
              status: "finished"
            }
          ];
        } else {
          this.uploadList = [];
        }
      }
    }
  }
};
</script>
<style>
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.fc-hide-btn .ivu-upload .ivu-upload {
  display: none;
}
.fc-upload-btn,
.fc-files {
  display: inline-block;
  width: 58px;
  height: 58px;
  text-align: center;
  line-height: 58px;
  border: 1px solid #c0ccda;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
  margin-right: 4px;
  box-sizing: border-box;
}

.fc-files > .ivu-icon {
  vertical-align: middle;
}
.fc-upload .fc-upload-cover {
  opacity: 0;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
  transition: opacity 0.3s;
}
.fc-upload .fc-upload-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.upload-btn {
  width: 58px;
  height: 58px;
  line-height: 58px;
}
.upload-tip {
  color: #999;
  line-height: 18px;
}
</style>